<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef2"
      :model="list"
      :rules="formRules"
      label-width="0px"
      v-loading="formLoading"
    >
    <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" type="index" width="70" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="数量" align="center" prop="countActual" />
      <el-table-column label="产品单位" align="center" prop="productUnitName" />
      <el-table-column label="产品规格" align="center" prop="productStandards" />
      <el-table-column label="供应商" min-width="150">
            <template #default="{ row,$index }">
              <el-form-item :prop="`${$index}.supplierId`" :rules="formRules.supplierId">
                <el-select
                v-if="row.supplierId !== undefined"
                  v-model="row.supplierId"
                  clearable
                  filterable
                  placeholder="请选择供供应商"
                   class="!w-240px"
                 
                   @mousedown="handleMouseDown(row)"
                >
                  <el-option
                    v-for="item in  supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <el-select
                  v-if="row.supplierId === undefined"
                  v-model="row.supplierId"
                  clearable
                  filterable
                  placeholder="请选择供供应商"
                  class="!w-240px"
                  @change="handleChange(row)"
                  @mousedown="handleMouseDown(row)"
                >
                  <el-option
                    v-for="item in  supplierList1"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row)"
            v-hasPermi="['erp:pri-warehouse-integra:update']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="sendBack(scope.row)"
            v-hasPermi="['erp:pri-warehouse-integra:update']"
            v-if="false"
          >
            退回
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</el-form>
    <!-- 表单弹窗：添加/修改 -->
    <DepPurchaseItemList ref="formRef1"  @success="getList" width = "40%"/>

    <DepPurchaseItemList1 ref="formRef3"  @success="getList"/>
    <template #footer>
      <!-- <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button> -->
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DepPurchaseItemApi,DepPurchaseItemVO } from '@/api/erp/deppurchaseitem'
import { PriWarehouseIntegraApi } from '@/api/erp/priwarehouseintegra'
import DepPurchaseItemList from './DepPurchaseItemList.vue'
import DepPurchaseItemList1 from './DepPurchaseItemList1.vue'
import { SupplierApi, SupplierVO } from '@/api/spd/purchase/supplier'

/** ERP 一级库整合单 表单 */
defineOptions({ name: 'PriWarehouseIntegraForm' })


const loading = ref(false) // 列表的加载中
const list = ref<DepPurchaseItemVO[]>([]) // 列表的数据
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
const supplierList1 = ref<SupplierVO[]>([]) // 供应商列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  integrateId: undefined,
  remark: undefined,
  opinion: undefined,
  status: undefined,
  processInstanceId: undefined,
})
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  integrateId: undefined,
  status: 0,
})

const formRules = reactive({
  supplierId: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
})


const formRef = ref() // 表单 Ref
const formRef2 = ref() // 表单 Ref

const handleChange = async (row: any) => {
  await DepPurchaseItemApi.updateDepPurchaseItemSupplier(row)
}

const handleMouseDown = async (row: any) => {
row.supplierId = undefined
supplierList1.value = await SupplierApi.getSupplierByProductId(row.productId)
}

const getList = async () => {
  loading.value = true
  try {
    list.value = []
    const data = await DepPurchaseItemApi.getDepPurchaseItemByPriWarehouseIntegraId(queryParams)
    list.value = data
  } finally {
    loading.value = false
  }
}

/** 打开弹窗 */
const open = async (type: string, integrateId?: String, id: number) => {
  dialogVisible.value = true
  dialogTitle.value = '详情'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (integrateId) {
    formLoading.value = true
    try {
      queryParams.integrateId = integrateId
      // 查询整合单
      formData.value = await PriWarehouseIntegraApi.getPriWarehouseIntegra(id)
      // 查询科室采购单
      // const data  = await DepPurchaseApi.getDepPurchasePage(queryParams)
       const data = await DepPurchaseItemApi.getDepPurchaseItemByPriWarehouseIntegraId(queryParams)
       list.value = data
console.log(list.value)
       supplierList.value = await SupplierApi.getSupplierSimpleList()
    } catch (error) {
      console.error('加载数据失败:', error)
      // 可选：弹窗提示用户或触发重试逻辑
    } finally {
      formLoading.value = false
    }
  }
}

/** 添加/修改操作 */
const formRef1 = ref()
const openForm = (type: string, row?: any) => {
  formRef1.value.open1(type, row,  queryParams.integrateId)
}

/** 添加/修改操作 */
const formRef3 = ref()
const sendBack = (row?: any) => {
  formRef3.value.open1(row,  queryParams.integrateId)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    formData.value.depPurchaseItems = list.value
    console.log(formData.value)
    if (formType.value === 'create') {
      await PriWarehouseIntegraApi.createPurPurchaseOrder(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await PriWarehouseIntegraApi.createPurPurchaseOrder(formData.value)
      message.success(t('common.createSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    integrateId: undefined,
    remark: undefined,
    opinion: undefined,
    status: undefined,
    processInstanceId: undefined,
  }
  formRef.value?.resetFields()
}
</script>